<template>
	<view class="container">
		<view class="box" v-if="loaded">
			<image class="shop-logo" :src="logo" alt="" />
			<view class="shop-name">{{name}}</view>
			<view v-if="ratio > 0" class="shop-ratio">此商户可参与单店免单，最高返{{user_back_ratio}}%</view>
			<view class="input-box flex-center">
				<text class="rmb">¥</text>
				<uni-easyinput
					trim="all" 
					type="digit" 
					v-model="amount"
					:focus="showFocus"
					placeholder="请输入支付金额"
					:inputBorder="false" 
					:styles="{color: '#2e2e2e', backgroundColor: '#fff'}" 
					primaryColor="#969799">	
				</uni-easyinput>
			</view>
			<view class="shop-btn" @click="pay">立即支付</view>
			<view v-show="amount > 0" class="shop-ratio-amount">支付后可排队免单：¥{{(amount * user_back_ratio / 100).toFixed(2)}}</view>
		</view>
		<!-- 余额支付弹窗 -->
		<balance-pop v-model="openBalance" :balance="user.balance" @pay="nextPay" @closeBalance="closeBalance"></balance-pop>
	</view>
</template>

<script>
	import { shopPayOrder, getUserDetail, getShopPaymentPayResult, shopDetail } from '@/http/apis.js';
	import { mapGetters, mapMutations } from "vuex";
	
	export default {
		name: 'mall-pay',
		data() {
			return {
				balancePay: false, // 是否余额支付
				amount: '',
				logo: '',
				name: '',
				ratio: '',
				shop_id: 0,
				orderCheck: null,
				user_back_ratio: 0,
				loading: false,
				loaded: false,
				showFocus: false,
				payCheck: null, // 三方支付后轮询
				openBalance: false,
			}
		},
		async onLoad(e) {
			await this.$onLaunched;
			this.shop_id = parseInt(e.id);
			this.getData();
		},
		onShow() {
			uni.showLoading();
			this.payCheck = setTimeout(() => {
				const {pay_status, payment_no} = getApp().globalData;
				if (pay_status === 1 && payment_no) {
					getApp().globalData.pay_status = 0;
					getApp().globalData.payment_no = ''
					this.payResult(payment_no);
					this.orderCheck = setInterval(() => {
						this.payResult(payment_no);
					}, 4 * 1000)
				} else if (pay_status === 2) {
					uni.hideLoading()
					getApp().globalData.pay_status = 0;
					getApp().globalData.payment_no = ''
				} else {
					uni.hideLoading()
				}
			}, 1500)
		},
		onHide() {
			clearInterval(this.orderCheck);
			clearTimeout(this.payCheck);
			this.orderCheck = null;
			this.payCheck = null;
		},
		computed: {
			...mapGetters(['user','configs']),
		},
		methods: {
			...mapMutations(['setUser']),
			getData() {
				uni.showLoading({});
				shopDetail({id: this.shop_id}).then(res => {
					this.shopInfo = res;
					this.logo = res.shop.thumbnail;
					this.name = res.shop.name;
					this.ratio = res.shop.back_ratio;
					// 商户最大免单比例
					this.configs.map(item => {
						if (item.config_key == 'shop_back_ratio_configs') {
							const back_ratios =  JSON.parse(item.config_value);
							back_ratios.map(item => {
								if (item.ratio <= this.ratio) {
									this.user_back_ratio = item.back;
								}
							})
						}
					})
					this.loaded = true;
					// uni.hideLoading({});
					// 此商家不支持线下支付或商家已下架
					if (res.shop.online_shop === 1 || res.shop.status !== 2) {
						uni.redirectTo({
							url: "/personal/error/index?type=1"
						})
					} else {
						this.showFocus = true;
					}
					console.log('success');
				}).catch(res => {
					uni.hideLoading({})
					this.loaded = true;
					uni.redirectTo({
						url: "/personal/error/index?type=1"
					})
				})
			},
			pay() {
				if (this.loading) return;
				if (this.amount > 0) {
					// 微信或者余额支付
					if (this.user.balance > 0) {
						this.openBalance = true;
					} else {
						this.nextPay();
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: '请输入支付金额'
					})
				}
			},
			closeBalance() {
				this.openBalance = false;
				this.balancePay = false;
			},
			nextPay(e) {
				this.balancePay = e;
				this.openBalance = false;
				this.loading = true;
				uni.showLoading();
				const params = {
					shop_id: this.shop_id,
					amount: parseInt(this.amount * 100),
					balance_pay_amount: this.balancePay ? this.user.balance : 0
				}
				shopPayOrder(params).then(res => {
					// 需要微信支付
					if (res.pay_info) {
						let _this = this;
						const pay_info = JSON.parse(res.pay_info)
						const accountInfo = uni.getAccountInfoSync();
						let envVersion = 'release';
						if (accountInfo) {
							envVersion = accountInfo.miniProgram.envVersion == 'release' ? 'release' : 'trial'
						}
						if (pay_info.pay_channel && pay_info.pay_channel === 2) {
							uni.openEmbeddedMiniProgram({
								appId: 'wxf0286c0d3b87bf34',
								path: 'pages/index/index?payment_no=' + pay_info.data.payment_no,
								envVersion: envVersion,
								success: function(res) {
									console.log('open success')
								},
								fail: function(req) {
									console.log('open fail', req)
									_this.wxPay(pay_info, res.payment_no)
								}
							})
						} else { // 此应用的微信支付
							_this.wxPay(pay_info, res.payment_no)
						}
						
					} else {
						this.payResult(res.payment_no);
						this.orderCheck = setInterval(() => {
							this.payResult(res.payment_no);
						}, 5 * 1000)
					}
				}).catch(res => {
					console.log(res);
					uni.hideLoading()
					uni.showToast({
						icon: 'none',
						title: res.msg || '支付失败'
					})
				})
			},
			wxPay(pay_info, payment_no) {
				uni.requestPayment({
				    provider: "wxpay", 
				    ...pay_info,
				    success(req) {
						_this.payResult(payment_no);
						_this.orderCheck = setInterval(() => {
							_this.payResult(payment_no);
						}, 5 * 1000)
					},
				    fail(e) {
						_this.loading = false;
						if (e.errMsg == "requestPayment:fail cancel") {
							uni.showToast({
								icon: 'none',
								title: '取消支付'
							})
						} else {
							uni.showToast({
								icon: 'none',
								title: '支付失败'
							})
						}
					}
				})
			},
			payResult(pid) {
				getShopPaymentPayResult({payment_no: pid}).then(res => {
					if (res && res.success) {
						if(this.balancePay) this.updateUser();
						uni.hideLoading();
						clearInterval(this.orderCheck)
						this.orderCheck = null;
						getApp().globalData.pay_status = 0;
						getApp().globalData.payment_no = ''
						uni.navigateTo({
							url: `/pages/mall/result?id=${res.payment_id}&name=${this.name}`
						})
					}
				})
			},
			// 如果是余额支付，更新用户的余额
			updateUser() {
				getUserDetail().then(res => {
					this.setUser(res)
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.flex {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.flex-center {
		display: flex;
		align-items: center;
	}
	.box {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 60rpx 20rpx 40rpx 20rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.container {
		width: 100%;
		min-height: 100vh;
		padding: 26rpx 24rpx 50rpx 24rpx;
		box-sizing: border-box;
		background-color: #F8FAFD;
		position: relative;
		.shop-logo {
			width: 180rpx;
			height: 180rpx;
			border-radius: 16rpx;
			margin-bottom: 22rpx;
		}
		.shop-name {
			color: #2e2e2e;
			font-size: 32rpx;
			line-height: 40rpx;
			margin-bottom: 8rpx;
		}
		.shop-ratio {
			color: #2e2e2e;
			font-size: 24rpx;
			line-height: 40rpx;
		}
		.input-box {
			margin-top: 114rpx;
			border-bottom: 2rpx solid #F1F1F1;
			height: 68rpx;
			width: 100%;
			color: #2e2e2e;
			font-size: 32rpx;
			.rmb {
				color: #2e2e2e;
				font-size: 68rpx;
				line-height: 68rpx;
			}
			::v-deep .uni-easyinput__content-input {
				font-size: 48rpx !important;
				color: #2e2e2e;
			}
		}
		.shop-btn {
			width: 100%;
			margin-top: 40rpx;
			color: #30240A;
			font-size: 28rpx;
			text-align: center;
			border-radius: 50rpx;
			height: 100rpx;
			line-height: 100rpx;
			background: linear-gradient(101deg, #FADF5D 19%, #F7D35D 80%);
		}
		.shop-ratio-amount {
			color: #F97028;
			font-size: 28rpx;
			margin-top: 30rpx;
			line-height: 44rpx;
		}
		
	}
	
	.balance {
		width: 100%;
		background-color: #fff;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		position: absolute;
		bottom: -100rpx;
		left: 0;
		z-index: 99;
		padding: 40rpx 40rpx;
		padding-bottom: 140rpx;
		box-sizing: border-box;
		overflow: hidden;
		.balance-top{
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 20rpx 0;
			&-txt{
				font-size: 24rpx;
				color: #999;
				margin-top: 20rpx;
			}
		}
		.balance-item {
			height: 72rpx;
		}
		.txt {
			color: #2e2e2e;
			font-size: 28rpx;
			height: 72rpx;
			line-height: 72rpx;
		}
		.select {
			width: 40rpx;
			height: 40rpx;
		}
		.check-icon {
			width: 40rpx;
			height: 40rpx;
		}
		.balance-btn {
			height: 72rpx;
			width: 100%;
			line-height: 72rpx;
			box-sizing: border-box;
			border-radius: 36rpx;
			background: linear-gradient(113deg, #FADF5D 18%, #F7D35D 81%);
			text-align: center;
			color: #30240A;
			font-size: 28rpx;
			margin-top: 30rpx;
		}
	}
</style>